<template>
<div>
  <div class="user-avatar-dropdown">
    <Dropdown @on-click="handleClick">
      <Badge :dot="!!messageUnreadCount">
        <Avatar src="https://img.zcool.cn/community/01786557e4a6fa0000018c1bf080ca.png@1280w_1l_2o_100sh.png"/>
      </Badge>
      {{name}}
      <Icon :size="18" type="md-arrow-dropdown"></Icon>
      <DropdownMenu slot="list">
        <!-- <DropdownItem name="message">
          消息中心<Badge style="margin-left: 10px" :count="messageUnreadCount"></Badge>
        </DropdownItem> -->
        <DropdownItem name="message">
          修改密码
        </DropdownItem>
        <DropdownItem name="logout">退出登录</DropdownItem>
      </DropdownMenu>
    </Dropdown>
  </div>
  <Modal :mask-closable="false" v-model="modal1" title="修改密码">
      <Form :model="formItem" :label-width="80">
        <FormItem label="原密码">
              <Input v-model="formItem.password" type="password" placeholder="请输入"></Input>
        </FormItem>
         <FormItem label="新密码">
              <Input v-model="formItem.newPassword" type="password" placeholder="请输入"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" size="large" @click="modal1=false">取消</Button>
        <Button type="primary" size="large" @click="ok">确定</Button>
      </div>
    </Modal>
</div>
</template>

<script>
import './user.less'
import { mapActions } from 'vuex'
import {updatePwd} from '@/api/user'
export default {
  name: 'User',
  data(){
    return {
      name:localStorage.getItem('recordUserName'),
      modal1: false,
      formItem: {
        id: localStorage.getItem('recordUserId'),
        password: '',
        newPassword:''
      },
    }
  },
  props: {
    userAvatar: {
      type: String,
      default: ''
    },
    messageUnreadCount: {
      type: Number,
      default: 0
    }
  },
  methods: {
    ...mapActions([
      'handleLogOut'
    ]),
    logout () {
      this.handleLogOut().then(() => {
        localStorage.clear();
        location.reload();
        this.$router.push({
          name: 'login'
        })
      })
    },
    message () {
      this.modal1=true;
      this.formItem={
        id: localStorage.getItem('recordUserId'),
        password: '',
        newPassword:''
      };
    },
    handleClick (name) {
      switch (name) {
        case 'logout': this.logout()
          break
        case 'message': this.message()
          break
      }
    },
    ok () {
        if(this.formItem.newPassword.length<4||this.formItem.newPassword.length>16){
          this.$Message.info('密度长度必须为4-16位')
          return false;
      }
        updatePwd(this.formItem).then(res => {
          if (res.code == 0) {
            this.$Message.info('修改成功');
            this.modal1 = false
          } else {
            this.$Message.info(res.message)
          }
        }).catch(err => {
          console.error('err>' + JSON.stringify(err))
        })

    }
  }
}
</script>
